package com.example.taobaou.ui.fragment;


import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.taobaou.R;
import com.example.taobaou.base.BaseFragment;
import com.example.taobaou.model.domain.Historys;
import com.example.taobaou.model.domain.IBsaeInfo;
import com.example.taobaou.model.domain.SearchRecommend;
import com.example.taobaou.model.domain.SearchResult;
import com.example.taobaou.presenter.impl.SearchPresenter;
import com.example.taobaou.ui.Custom.TextFlowLayout;
import com.example.taobaou.ui.adapter.HomePagerContentAdapter;
import com.example.taobaou.utils.KetboardUtil;
import com.example.taobaou.utils.LogUtils;
import com.example.taobaou.utils.PresenterManager;
import com.example.taobaou.utils.SizeUtils;
import com.example.taobaou.utils.TicketUtil;
import com.example.taobaou.utils.TostUtils;
import com.example.taobaou.view.ISearchPageCallBack;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchFragment extends BaseFragment implements ISearchPageCallBack, HomePagerContentAdapter.OnListItemClickListener, TextFlowLayout.OnFlowTextItemClickListener {


    private SearchPresenter mSearchPresenter;
    private TextFlowLayout mHistory;
    private TextFlowLayout mRecommend;
    private View historyContainer;
    private View recommendContainer;
    private ImageView mDeleted;
    private RecyclerView searchResult;
    private HomePagerContentAdapter adapter;
    private TwinklingRefreshLayout refreshLayout;
    private ImageView remove;
    private EditText searchInputBox;
    private TextView searchBtn;
    private View goSearch;

    public SearchFragment() {
        // Required empty public constructor
    }

    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_search_title_layout, container, false);
    }

    @Override
    protected int getRootViewResID() {
        return R.layout.fragment_search;
    }

    @Override
    protected void release() {
        mSearchPresenter.unregisiterViewCallback(this);
    }


    @Override
    protected void onRetryClick() {
        if (mSearchPresenter != null) {
            mSearchPresenter.reSesarch();
        }
    }

    @Override
    protected void initView(View rootView) {
        setState(State.SUCCESS);

        mHistory = rootView.findViewById(R.id.search_history_view);
        mRecommend = rootView.findViewById(R.id.search_recommend_view);
        historyContainer = rootView.findViewById(R.id.history_container);
        recommendContainer = rootView.findViewById(R.id.recommend_container);
        mDeleted = rootView.findViewById(R.id.search_history_delete);


        searchResult = rootView.findViewById(R.id.srarch_result_list);
        searchResult.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new HomePagerContentAdapter();
        searchResult.setAdapter(adapter);
        searchResult.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = SizeUtils.dip2px(getContext(), 2);
                outRect.bottom = SizeUtils.dip2px(getContext(), 2);
            }
        });

        refreshLayout = rootView.findViewById(R.id.search_result_refresh);
        refreshLayout.setEnableLoadmore(true);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableOverScroll(true);

        remove = rootView.findViewById(R.id.remove_btm);
        searchInputBox = rootView.findViewById(R.id.search_input_box);
        searchBtn = rootView.findViewById(R.id.btn_search);

        goSearch = rootView.findViewById(R.id.go_search);
    }

    @Override
    protected void initListener() {
        super.initListener();
        /**
         * 删除历史记录
         */
        mDeleted.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSearchPresenter.deletedHistories();
            }
        });

        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                //下拉加载更多
                if (mSearchPresenter != null) {
                    mSearchPresenter.onLoaderMore();
                }
            }
        });

        adapter.setOnListItemClickListener(this);
        /**
         * 通过小键盘搜索内容
         */
        searchInputBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH && mSearchPresenter != null) {
                    String keyWord = textView.getText().toString().trim();
                    if (TextUtils.isEmpty(keyWord)) {
                        return false;
                    }
                    //mSearchPresenter.doSearch(keyWord);
                    toSearch(keyWord);
                }
                return false;
            }
        });
        /**
         * 输入框内叉号根据输入框是否有内容判断是否显示
         * 搜索按钮输入框有内容显示搜索，无内容显示取消
         */
        searchInputBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                remove.setVisibility(hasInput(false) ? View.VISIBLE : View.GONE);
                searchBtn.setText(hasInput(true) ? "搜索" : "取消");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        /**
         * 输入框内叉号点击后将输入框内内容置空
         */
        remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchInputBox.setText("");
                swich2HistoryPage();
            }
        });
        /**
         *搜索按钮
         */
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击后隐藏键盘
                KetboardUtil.hide(getContext(), view);
                //输入框有内容就搜索，无内容则取消
                if (hasInput(true)) {
                    if (mSearchPresenter != null) {
                        //mSearchPresenter.doSearch(searchInputBox.getText().toString());
                        toSearch(searchInputBox.getText().toString());
                    }
                }
            }
        });

        mHistory.setOnFlowTextItemClickListener(this);
        mRecommend.setOnFlowTextItemClickListener(this);
    }

    /**
     * 切换到历史和推荐界面
     */
    private void swich2HistoryPage() {
        if (mSearchPresenter != null) {
            mSearchPresenter.getHistories();
        }
        if (mRecommend.getmTextList().size() != 0) {
            recommendContainer.setVisibility(View.VISIBLE);
        }
        refreshLayout.setVisibility(View.GONE);

    }

    /**
     * 获取输入框内容同时判断是否需要去除空格
     * ture 去掉空格 false 不需要去
     *
     * @param containSpace
     * @return
     */
    private boolean hasInput(boolean containSpace) {
        if (containSpace) {
            return searchInputBox.getText().toString().trim().length() > 0;
        } else {
            return searchInputBox.getText().toString().length() > 0;
        }
    }

    @Override
    protected void initPresenter() {
        mSearchPresenter = PresenterManager.getInstance().getSearchPresenter();
        mSearchPresenter.registerViewCallback(this);
        mSearchPresenter.getRecommendWords();
        mSearchPresenter.getHistories();
    }

    @Override
    public void onHistoriesLoaded(Historys historys) {

        if (historys == null || historys.getHistorys().size() == 0) {
            historyContainer.setVisibility(View.GONE);
        } else {
            historyContainer.setVisibility(View.VISIBLE);
            mHistory.setTextList(historys.getHistorys());
            LogUtils.d(this,"历史记录"+historys.getHistorys());
        }
    }

    @Override
    public void onHistoriesDeleted() {
        if (mSearchPresenter != null) {
            mSearchPresenter.getHistories();
        }
    }

    @Override
    public void onSearchSuccess(SearchResult result) {
        LogUtils.d(this, " result----------------------->" + result);
        setState(State.SUCCESS);
        //搜索成功后先隐藏掉历史记录和推荐
        recommendContainer.setVisibility(View.GONE);
        historyContainer.setVisibility(View.GONE);
        //显示搜索结果
        refreshLayout.setVisibility(View.VISIBLE);
        adapter.loadData(result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
    }

    @Override
    public void onLoadedMore(SearchResult result) {
        //加载更多
        List<SearchResult.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> moreData =
                result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data();
        adapter.addData(moreData);
        TostUtils.showToast("加载了" + moreData.size() + "件商品~");
        refreshLayout.finishLoadmore();

    }

    @Override
    public void onLoadedMoreError() {
        TostUtils.showToast("网络出错了，请检查后重试 ");
        refreshLayout.finishLoadmore();
    }

    @Override
    public void onLoadMoreEmpty() {
        TostUtils.showToast("没有更多宝贝了~");
        refreshLayout.finishLoadmore();
    }

    @Override
    public void onRecommendWordsLoaded(List<SearchRecommend.DataBean> recommend) {

        List<String> recommendWord = new ArrayList<>();
        for (SearchRecommend.DataBean dataBean : recommend) {
            recommendWord.add(dataBean.getKeyword());
        }
        if (recommendWord == null || recommendWord.size() == 0) {
            recommendContainer.setVisibility(View.GONE);

        } else {
            recommendContainer.setVisibility(View.VISIBLE);
            mRecommend.setTextList(recommendWord);
            LogUtils.d(this, "推荐词个数" + recommend.size());
        }


    }

    @Override
    public void onNatworkError() {
        setState(State.ERROR);
    }

    @Override
    public void onLoading() {
        setState(State.LOADING);
    }

    @Override
    public void onEmpty() {
        setState(State.EMPTY);
    }

    @Override
    public void onItemClick(IBsaeInfo item) {
        TicketUtil.toTicketPage(getContext(), item);
    }

    @Override
    public void onFlowTextItemClick(String text) {
        toSearch(text);
    }

    private void toSearch(String text) {
        if (mSearchPresenter != null) {
            searchResult.scrollToPosition(0);
            searchInputBox.setText(text);
            searchInputBox.setFocusable(true);
            searchInputBox.requestFocus();
            searchInputBox.setSelection(text.length(),text.length());
            mSearchPresenter.doSearch(text);
        }
    }
}
